<template>
  <div class="min-h-screen bg-gray-50 flex flex-col">

    <!-- 主要内容 -->
    <div class="flex-1 max-w-screen-md mx-auto px-6 py-6">
      <!-- 表单 -->
      <div class="bg-white rounded-2xl border-2 shadow-sm p-6 border-gray-200">
        <!-- 旧密码 -->
        <div class="mb-5">
          <label class="block text-base font-medium text-gray-800 mb-3">旧密码</label>
          <div class="relative">
            <input 
              v-model="form.oldPassword"
              :type="showOldPassword ? 'text' : 'password'"
              placeholder="请输入当前密码"
              class="w-full px-5 py-4 border border-gray-200 rounded-xl bg-white/80 backdrop-blur focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent text-base"
              :class="{ 'border-red-500': errors.oldPassword }"
            />
            <button 
              type="button"
              @click="showOldPassword = !showOldPassword"
              class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
            >
              <svg v-if="!showOldPassword" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
              </svg>
              <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L13.12 7.5m-3.242 8.486L15 15.75M21 12a9.97 9.97 0 01-1.563 3.029m-3.308-1.575a3 3 0 110-4.242m4.242 4.242L18.5 15.75M14.121 14.121L15.75 12m-2.629-6.364A10.05 10.05 0 0112 5c4.478 0 8.268 2.943 9.543 7"/>
              </svg>
            </button>
          </div>
          <div v-if="errors.oldPassword" class="text-red-500 text-sm mt-2">{{ errors.oldPassword }}</div>
        </div>

        <!-- 新密码 -->
        <div class="mb-5">
          <label class="block text-base font-medium text-gray-800 mb-3">新密码</label>
          <div class="relative">
            <input 
              v-model="form.newPassword"
              :type="showNewPassword ? 'text' : 'password'"
              placeholder="请输入新密码（至少6位）"
              class="w-full px-5 py-4 border border-gray-200 rounded-xl bg-white/80 backdrop-blur focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent text-base"
              :class="{ 'border-red-500': errors.newPassword }"
            />
            <button 
              type="button"
              @click="showNewPassword = !showNewPassword"
              class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
            >
              <svg v-if="!showNewPassword" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
              </svg>
              <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L13.12 7.5m-3.242 8.486L15 15.75M21 12a9.97 9.97 0 01-1.563 3.029m-3.308-1.575a3 3 0 110-4.242m4.242 4.242L18.5 15.75M14.121 14.121L15.75 12m-2.629-6.364A10.05 10.05 0 0112 5c4.478 0 8.268 2.943 9.543 7"/>
              </svg>
            </button>
          </div>
          <div v-if="errors.newPassword" class="text-red-500 text-sm mt-2">{{ errors.newPassword }}</div>
        </div>

        <!-- 确认新密码 -->
        <div class="mb-6">
          <label class="block text-base font-medium text-gray-800 mb-3">确认新密码</label>
          <div class="relative">
            <input 
              v-model="form.confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="请再次输入新密码"
              class="w-full px-5 py-4 border border-gray-200 rounded-xl bg-white/80 backdrop-blur focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent text-base"
              :class="{ 'border-red-500': errors.confirmPassword }"
            />
            <button 
              type="button"
              @click="showConfirmPassword = !showConfirmPassword"
              class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
            >
              <svg v-if="!showConfirmPassword" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
              </svg>
              <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L13.12 7.5m-3.242 8.486L15 15.75M21 12a9.97 9.97 0 01-1.563 3.029m-3.308-1.575a3 3 0 110-4.242m4.242 4.242L18.5 15.75M14.121 14.121L15.75 12m-2.629-6.364A10.05 10.05 0 0112 5c4.478 0 8.268 2.943 9.543 7"/>
              </svg>
            </button>
          </div>
          <div v-if="errors.confirmPassword" class="text-red-500 text-sm mt-2">{{ errors.confirmPassword }}</div>
        </div>

        <!-- 提交按钮 -->
        <button 
          @click="handleSubmit"
          :disabled="isSubmitting"
          class="w-full bg-brand-500 text-white py-4 rounded-xl font-medium hover:bg-brand-600 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 disabled:bg-gray-400 disabled:cursor-not-allowed text-base"
        >
          <span v-if="!isSubmitting">确认修改</span>
          <span v-else class="flex items-center justify-center">
            <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            修改中...
          </span>
        </button>
      </div>

      <!-- 提示信息 -->
      <div class="mt-4 text-xs text-gray-500">
        <p>• 新密码长度至少6位</p>
        <p>• 修改成功后需要重新登录</p>
      </div>
    </div>

    <!-- 成功弹窗 -->
    <div v-if="showSuccessModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 mx-4 max-w-sm w-full">
        <div class="text-center">
          <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg class="w-6 h-6 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">密码修改成功</h3>
          <p class="text-gray-600 mb-4">请重新登录系统</p>
          <button 
            @click="handleSuccessConfirm"
            class="w-full bg-brand-500 text-white py-2 rounded-lg font-medium hover:bg-brand-600 text-sm"
          >
            重新登录
          </button>
        </div>
      </div>
    </div>

    <!-- 失败弹窗 -->
    <div v-if="showErrorModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 mx-4 max-w-sm w-full">
        <div class="text-center">
          <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg class="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">修改失败</h3>
          <p class="text-gray-600 mb-4">{{ modalMessage }}</p>
          <button 
            @click="showErrorModal = false"
            class="w-full bg-brand-500 text-white py-2 rounded-lg font-medium hover:bg-brand-600 text-sm"
          >
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { updatePasswordByOld } from '../api/auth'

const router = useRouter()

// 表单数据
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 错误信息
const errors = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 显示密码状态
const showOldPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)

    // 提交状态
const isSubmitting = ref(false)
const showSuccessModal = ref(false)
const showErrorModal = ref(false)
const modalMessage = ref('')

// 返回上一页
const goBack = () => {
  router.back()
}

// 表单验证
const validateForm = () => {
  // 清空错误信息
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })

  let isValid = true

  // 验证旧密码
  if (!form.oldPassword.trim()) {
    errors.oldPassword = '请输入旧密码'
    isValid = false
  }

  // 验证新密码
  if (!form.newPassword.trim()) {
    errors.newPassword = '请输入新密码'
    isValid = false
  } else if (form.newPassword.length < 6) {
    errors.newPassword = '新密码长度至少6位'
    isValid = false
  }

  // 验证确认密码
  if (!form.confirmPassword.trim()) {
    errors.confirmPassword = '请确认新密码'
    isValid = false
  } else if (form.confirmPassword !== form.newPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }

  // 验证新旧密码不能相同
  if (form.oldPassword && form.newPassword && form.oldPassword === form.newPassword) {
    errors.newPassword = '新密码不能与旧密码相同'
    isValid = false
  }

  return isValid
}

// 处理提交
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  isSubmitting.value = true

  try {
    const result = await updatePasswordByOld(form.oldPassword, form.newPassword)
    
    if (result.success) {
      showSuccessModal.value = true
    } else {
      // 显示错误弹窗
      modalMessage.value = result.message || '修改密码失败'
      showErrorModal.value = true
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    modalMessage.value = '网络错误，请重试'
    showErrorModal.value = true
  } finally {
    isSubmitting.value = false
  }
}

// 处理成功确认
const handleSuccessConfirm = () => {
  showSuccessModal.value = false
  
  // 清空本地token
  const TOKEN_KEY = 'satoken'
  const TOKEN_EXPIRE_KEY = 'satoken_expire'
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(TOKEN_EXPIRE_KEY)
  console.log('密码修改成功，已清空本地token')
  
  // 跳转到登录页
  router.push('/login')
}
</script>